package com.hln.jingwushi.utils

import android.util.Log
import com.zgkxzx.modbus4And.requset.ModbusReq
import com.zgkxzx.modbus4And.requset.OnRequestBack
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.ThreadFactory


class EnvironmentalDetectionManager {


    companion object {
        private val environmentalDetectionManager = EnvironmentalDetectionManager()
        fun instance(): EnvironmentalDetectionManager {
            return environmentalDetectionManager
        }
    }

    var environmentalCB: EnvironmentalCB? = null

    var executorService: ExecutorService = Executors.newSingleThreadExecutor(
        ThreadFactory { r ->
            val thread = Thread(r)
            thread.name = "readTemp"
            thread
        })


    private var tempRunnable = Runnable {
        // 在这里执行任务
        while (true) {
            ModbusReq.getInstance().readInputRegisters(object : OnRequestBack<ShortArray> {
                override fun onSuccess(data: ShortArray) {
                    environmentalCB?.notify(data)
                    Log.d("asd", "readInputRegisters onSuccess ${data[0].toInt()} , ${data[1].toInt()}, ${data[2].toInt()} ")
                }

                override fun onFailed(msg: String) {
                    Log.e("asd", "readInputRegisters onFailed $msg")
                }
            }, 1, 100, 10)
            Thread.sleep(5000)
        }
    }


    fun startTask() {
        executorService.execute(tempRunnable)
    }

    fun stopTask() {
        removeLister()
        executorService.shutdown()
    }

    fun setLister(environmentalCB: EnvironmentalCB) {
        this.environmentalCB = environmentalCB
    }

    fun removeLister() {
        this.environmentalCB = null
    }


}